<?php

namespace App\Http\Controllers\Api\V1\Mes;

use App\Helpers\ResponseHelper;
use App\Helpers\V1\AuthMenuHelper;
use App\Http\Controllers\Controller;
use App\Models\Mes\AuthMenu;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AuthMenuController extends Controller
{
    /**
     * 菜单列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request)
    {
        try {
            $result = AuthMenu::query()
                ->orderBy("sort", "asc")
                ->get();
            $list = AuthMenuHelper::getTree($result);
            $return = compact("list");
        } catch (\Exception $e) {
            return ResponseHelper::json($e->getCode() ?: 20001, $e->getMessage());
        }
        return ResponseHelper::json(0, "success", $return);
    }

    /*
     * 添加
     */
    public function create(Request $request) : JsonResponse
    {
        try {
            $data = $request->all();
            AuthMenuHelper::validateData($data);
            AuthMenu::query()->create($request->only(["pid", "name", "flag"]));
        } catch (\Exception $e) {
            return ResponseHelper::json($e->getCode() ?: 20001, $e->getMessage());
        }
        return ResponseHelper::json(0, "操作成功");
    }

    public function modify(Request $request) :JsonResponse
    {
        try {
            $data = $request->all();
            AuthMenuHelper::validateData($data);
            $menu = AuthMenu::query()->find($data["id"]);
            $data = $request->only(["pid", "name", "flag"]);
            foreach ($data as $key => $val) {
                $menu->{$key} = $val;
            }
            $menu->save();
        } catch (\Exception $e) {
            return ResponseHelper::json($e->getCode() ?: 20001, $e->getMessage());
        }
        return ResponseHelper::json(0, "操作成功");
    }

    /*
     * 删除
     */
    public function delete(Request $request) :JsonResponse
    {
        try {
            $menu = AuthMenu::query()->find($request->input("id"));
            if (AuthMenu::query()->where("pid", $menu->id)->exists()) {
                throw new \Exception("该功能下存在子功能，请先删除子功能");
            }
            $menu->delete();
        } catch (\Exception $e) {
            return ResponseHelper::json($e->getCode() ?: 20001, $e->getMessage());
        }
        return ResponseHelper::json(0, "操作成功");
    }
}
